#include "thread.h"
#include <stdio.h>
#include <assert.h>
//#include <pthread.h>
#include <stdlib.h>

struct fib {
  int n;
  unsigned long long result;
};


void * fibo_n(void *arg) {

  struct fib *f = (struct fib *)arg;

  
  if(f->n <= 1){
    f->result = f->n;
  }
  
  if(f->n > 1) {

    thread_t t1, t2;
    
    //struct fib f1,f2;
    
    struct fib *f1,*f2;
    f1 = malloc(sizeof(struct fib));
    f2 = malloc(sizeof(struct fib));
    unsigned long long *ret1 = malloc(sizeof(*ret1));
    unsigned long long *ret2 = malloc(sizeof(*ret2));
    
    f1->n = f->n - 1;
    f2->n = f->n - 2;

    
    /*
     pthread_create(&t2, NULL, fibo_n, (void*)f1);
     pthread_create(&t2, NULL, fibo_n, (void*)f2);
    */


     thread_create(&t1, fibo_n, (void*)f1); 
     thread_create(&t2, fibo_n, (void*)f2);

     thread_join(t1, (void **)ret1);
     thread_join(t2, (void **)ret2);
 
    f->result = f1->result + f2->result;

    free(f1);
    free(f2);
  }

  thread_exit(NULL);
}


int main(int argc, char* argv[]) {

  struct fib *f;
  thread_t t;
  f= malloc(sizeof(struct fib));
  f->n = atoi(argv[1]);
  f->result = 0;

  thread_create(&t, fibo_n, (void*)f); 
  thread_join(t, NULL);

  printf("Resultat fibo(%d) = %lld\n", f->n, f->result);
  free(f);
  
  return EXIT_SUCCESS;

}
